import { Options, PipelineOperator } from "../../core";
import { Iterator } from "../../lazy";
import { Query } from "../../query";
import { AnyObject } from "../../types";
import { AsyncIterator } from "../../async/lazy";
/**
 * Filters the document stream to allow only matching documents to pass unmodified into the next pipeline stage.
 *
 * See {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation/match usage}.
 *
 * @param collection
 * @param expr
 * @param options
 * @returns
 */
export const $match: PipelineOperator = (
  collection: Iterator|AsyncIterator,
  expr: AnyObject,
  options: Options
): Iterator|Promise<AsyncIterator> => {
  const q = new Query(expr, options);
  if(options.isAsync) {
    return Promise.resolve(collection as AsyncIterator).then((collection) => {
      collection.addCondition(expr)
      return collection.filter((o: AnyObject) => q.test(o));
    });
  }
  return (collection as Iterator).filter((o: AnyObject) => q.test(o));
};
